﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace xCodeCounter
{
	public partial class MainWnd : Form
	{
		public MainWnd()
		{
			InitializeComponent();
		}

		private void MainWnd_Load(object sender, EventArgs e)
		{
			string val = Config.GetString("path");
			if (val.Length > 0)
			{
				txtPath.Text = val;
			}
		}

		private void MainWnd_FormClosing(object sender, FormClosingEventArgs e)
		{
			Config.WriteString("path", txtPath.Text);
		}

		private void btnBrows_Click(object sender, EventArgs e)
		{
			FolderBrowserDialog dlg = new FolderBrowserDialog();
			dlg.ShowNewFolderButton = false;
			dlg.SelectedPath = txtPath.Text;
			if (dlg.ShowDialog(this) == DialogResult.OK)
			{
				txtPath.Text = dlg.SelectedPath;
			}
		}

		private void btnCountFiles_Click(object sender, EventArgs e)
		{
			SortedList<string, int> mm = new SortedList<string, int>();
			IEnumerable<string> files = Directory.EnumerateFiles(txtPath.Text, "*", SearchOption.AllDirectories);
			foreach (string file in files)
			{
				string ext = Path.GetExtension(file);
				if (mm.ContainsKey(ext))
				{
					mm[ext]++;
				}
				else
				{
					mm[ext] = 1;
				}
			}

			int min = int.Parse(txtMin.Text);
			string info = "";
			int count = 0;
			foreach (string ext in mm.Keys)
			{
				if (mm[ext] < min)
				{
					continue;
				}
				info += string.Format("{0,10} = {1}\t", ext, mm[ext]);
				count++;
				if (count%5 == 0)
				{
					//info += "\n";
				}
			}
			MessageBox.Show(info);
		}

		int CountOneFile(string fileName)
		{
			using (StreamReader sr = new StreamReader(fileName))
			{
				string full = sr.ReadToEnd();
				int c = full.Split('\n').Length;
				return c;
			}
		}

		private void btnCountLines_Click(object sender, EventArgs e)
		{
			string[] ay = txtExts.Text.Split(',');
			HashSet<string> hs = new HashSet<string>(ay);

			int count = 0;
			IEnumerable<string> files = Directory.EnumerateFiles(txtPath.Text, "*", SearchOption.AllDirectories);
			foreach (string file in files)
			{
				string ext = Path.GetExtension(file);
				if (ext.Length == 0)
				{
					continue;
				}
				ext = ext.Substring(1);
				if (hs.Contains(ext))
				{
					count += CountOneFile(file);
				}
			}
			MessageBox.Show(string.Format("line count is: {0}", count));
		}

	}
}
